<template>
  <div class="app-container" :size="size">
    <div class="goods-info-container">
      <div class="goods-info-header">
        <div class="goods-info-header-title">
          <span>新增商品</span>
        </div>
        <div class="flex-buttons" style="float: right">
          <el-button icon="el-icon-finished" class="config-btn" @click="submitForm">确 定</el-button>
          <el-button icon="el-icon-close" class="cancel-btn" @click="close">取 消</el-button>
        </div>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-tabs type="border-card" v-model="activeName">
          <el-tab-pane name="main" label="基础信息">
            <el-form-item label="商品编码" prop="assNumber">
              <el-input v-model="form.assNumber" placeholder="商品编号" disabled/>
            </el-form-item>
            <el-row>
              <el-col :span="24">
                <el-form-item label="商品名称" prop="goodsName">
                  <el-input v-model="form.goodsName" placeholder="请输入商品名称"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="品牌" prop="brandId">
                  <treeselect
                    v-model="form.brandId"
                    :options="options.brandOptions"
                    :size="size"
                    placeholder="请选择商品品牌"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="商品类型" >
                  <el-cascader
                    :options="options.gTypeOptions"
                    v-model="form.typeIdList"
                    :props="{ checkStrictly: true }"
                    @change="handleTypeInput"
                    filterable clearable style="width: 100%"
                  >
                    <template slot-scope="{ node, data }">
                      <span>{{ data.label }}</span>
                      <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                    </template>
                  </el-cascader>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="封面图片" prop="image">
              <el-button class="select-btn" style="position: absolute;" icon="el-icon-folder-opened" plain
                         @click="openSelectFmImage"
              >
                选择已上传图片
              </el-button>
              <div class="image-list">
                <div class="image-item">
                  <image-preview v-if="form.image" :src="form.image" :width="80" :height="80"/>
                </div>
              </div>
            </el-form-item>
            <el-form-item label="轮播图片" prop="image">
              <el-button class="select-btn" style="position: absolute;" icon="el-icon-folder-opened" plain
                         @click="openSelectLbImage"
              >
                选择已上传图片
              </el-button>
              <draggable class="image-list" v-model="form.params.lbImages">
                <div class="image-item" v-for="(item, index) in form.params.lbImages" :key="index">
                  <image-preview :src="form.params.lbImages[index]" :width="80" :height="80"
                                 :can-delete="true" @remove="handleDelLbImage(index)"
                  />
                </div>
              </draggable>
            </el-form-item>
            <el-row>
              <el-col :span="8">
                <el-form-item label="状态" prop="delFlag">
                  <el-radio-group v-model="form.delFlag">
                    <el-radio
                      v-for="dict in dict.type.sys_normal_disable"
                      :key="dict.value"
                      :label="dict.value"
                    >{{ dict.label }}
                    </el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="config" label="价格库存">
            <el-row>
              <el-form-item label="属性分类">
                <el-transfer
                  v-model="form.assorts"
                  target-order="push"
                  :data="options.attrOptions"
                  :titles="['属性列表', '分类列表']"
                  @change="handleTransferChange"
                  @right-check-change="handleRightCheckChange"
                >
                </el-transfer>
              </el-form-item>
            </el-row>
            <el-row>
              <sku-tag :attrOptions="options.attrOptions" />
<!--              <el-form-item label="商品规格" >
              </el-form-item>-->
            </el-row>
            <el-row>
              <el-button class="add-btn" :disabled="withoutAssorts()" @click="handleGoodsAdd">添加</el-button>
            </el-row>
            <el-row>
              <el-form-item label="规格明细">
                <span style="padding-right: 15px;">批量设置</span>
                <el-button
                  type="text"
                  v-for="item in form.goodsInfo.tableHeader"
                  @change="mulChangeType(item.prop)"
                >{{ item.label }}</el-button>
              </el-form-item>
            </el-row>
            <el-table
              border stripe
              :data="form.goodsInfo.list"
              style="margin-top: 10px"
            >
<!--                            @selection-change="handleAttrSelectionChange"-->
              <el-table-column type="selection" width="50" align="center" />
              <template v-for="item in form.goodsInfo.tableHeader">
                <el-table-column
                  :key="item.prop"
                  :prop="item.prop"
                  :label="item.label"
                  align="center"
                  :width="item.width"
                >
                  <template slot-scope="scope">
                    <template v-if="item.inputType === 'input'">
                      <el-input v-model="scope.row[item.prop]" @change="handleRowInputChange(scope.$index, scope.row)"/>
                    </template>
                    <template v-else>
                      {{ scope.row[item.prop] }}
                    </template>
                  </template>
                </el-table-column>
              </template>
            </el-table>
          </el-tab-pane>
          <el-tab-pane name="assSort" label="共通属性">
            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button
                  class="select-btn"
                  plain
                  icon="el-icon-plus"
                  :disabled="withoutAssorts()"
                  @click="handleConfigAdd"
                >新增
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  class="add-btn"
                  plain
                  icon="el-icon-plus"
                  :disabled="withoutAssorts()"
                  @click="handleConfigAddLine"
                >新增行
                </el-button>
              </el-col>
              <el-col :span="1.5">
                <el-button
                  class="del-btn"
                  plain
                  icon="el-icon-delete"
                  :disabled="form.config.multiple"
                  @click="handleConfigDel"
                >删除
                </el-button>
              </el-col>
            </el-row>
            <el-row>

              <el-table
                border
                ref="dragTable"
                :data="form.config.configList"
                v-loading="form.config.loading"
                row-key="gConfigId"
                :row-class-name="configRowClassName"
                @selection-change="handleSelectionChange"
              >
                <el-table-column type="selection" width="50" align="center"/>
                <el-table-column label="序号" prop="index" width="50" align="center" class-name="allowDrag"/>
                <el-table-column label="属性" prop="attr" align="center">
                  <template slot-scope="scope">
                    <el-cascader
                      v-model="scope.row.attr"
                      :options="options.rowAttrOptions"
                      :show-all-levels="false"
                      filter clearable
                      @change="handleAttrIdChange(scope.row, $event)"
                      placeholder="请选择商品属性"
                    ></el-cascader>
                  </template>
                </el-table-column>
                <el-table-column label="属性名称" prop="configName" align="center" :render-header="renderHeader">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.configName" placeholder="属性名称"/>
                  </template>
                </el-table-column>
                <el-table-column label="属性值" prop="valueId" align="center" :render-header="renderHeader">
                  <template slot-scope="scope">
                    <el-select
                      v-if="scope.row.multiple"
                      v-model="scope.row.valueIds"
                      allow-create clearable filterable multiple collapse-tags
                      placeholder="属性值"
                      @change="handleAttrValChange(scope.row, $event)"
                    >
                      <el-option
                        v-for="op in scope.row.attrValOptions"
                        :key="op.valueId+''"
                        :label="op.valueLabel+' ['+op.valueId+']'"
                        :value="op.valueId+''"
                      />
                    </el-select>
                    <el-select
                      v-else
                      v-model="scope.row.valueId"
                      allow-create clearable filterable
                      placeholder="属性值"
                      @change="handleAttrValChange(scope.row, $event)"
                    >
                      <el-option
                        v-for="op in scope.row.attrValOptions"
                        :key="op.valueId+''"
                        :label="op.valueLabel+' ['+op.valueId+']'"
                        :value="op.valueId+''"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="属性值" prop="valueName" align="center">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.valueName" placeholder="属性值" disabled/>
                  </template>
                </el-table-column>
                <el-table-column label="自定义属性值" prop="configVal" align="center" :render-header="renderHeader">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.configVal" clearable placeholder="自定义属性值"/>
                  </template>
                </el-table-column>
                <el-table-column label="状态" prop="delFlag" width="100" align="center">
                  <template slot-scope="scope">
                    <el-switch
                      v-model="scope.row.delFlag"
                      active-value="0"
                      inactive-value="1"
                    ></el-switch>
                  </template>
                </el-table-column>
              </el-table>
            </el-row>
          </el-tab-pane>
          <el-tab-pane name="details" label="商品详情">
            <el-form-item label="详情图片" prop="image">
              <el-button class="select-btn" style="position: absolute;" icon="el-icon-folder-opened" plain
                         @click="openSelectXqImage"
              >
                选择已上传图片
              </el-button>
              <draggable class="image-list" v-model="form.desc.xqImages">
                <div class="image-item" v-for="(item, index) in form.desc.descImages" :key="index">
                  <image-preview :src="form.desc.descImages[index]" :width="80" :height="80"
                                 :can-delete="true" @remove="handleDelXqImage(index)"
                  />
                </div>
              </draggable>
            </el-form-item>
            <el-form-item label="自定义详情" prop="delFlag">
              <el-radio-group v-model="form.desc.delFlag">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="form.desc.delFlag === '0'">
              <el-form-item label="自定义内容" prop="content">
                <editor v-model="form.desc.content" :min-height="250"/>
              </el-form-item>
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.desc.remark" type="textarea"/>
              </el-form-item>
            </template>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </div>


    <select-image ref="selectFm" :params="{ imageType: '1' }" @ok="handleSelectFmOk"/>
    <select-image ref="selectLb" :params="{ imageType: '2', limit: 10, selectedList: form.params.lbImages }"
                  @ok="handleSelectLbOk"
    />
    <select-image ref="selectXq" :params="{ imageType: '3', limit: 10, selectedList: form.desc.descImages }"
                  @ok="handleSelectXqOk"
    />
    <select-attr ref="selectAttr" @ok="handleSelectAttr"/>
  </div>
</template>
<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import SelectImage from '@/views/goods/images/components/select.vue'
import SelectAttr from '@/views/goods/attr/components/select.vue'
import { addMain } from '@/api/goods/main'
import { treeSelect as optionBrandSelect } from '@/api/goods/brand'
import { treeSelect as optionGTypeSelect } from '@/api/goods/type'
import { getAttr, treeSelect as optionAttrSelect, findAttrsWithoutConfig } from '@/api/goods/attr'
import draggable from 'vuedraggable'
import ImagePreview from '@/components/ImagePreview'
import SkuTag from './components/sku-tag.vue'
import Sortable from 'sortablejs'

export default {
  name: 'AddGoods',
  components: { Treeselect, SelectImage, SelectAttr, draggable, ImagePreview, SkuTag },
  dicts: ['sys_normal_disable', 'sys_goods_sj_status'],
  computed: {
    size() {
      return this.$store.getters.size
    }
  },
  data() {
    // 定义自定义验证函数
    const validatePositiveInteger = (rule, value, callback) => {
      if (!value) {
        return callback(new Error('请输入数字'))
      }
      setTimeout(() => {
        if (!Number.isInteger(Number(value)) || Number(value) <= 0) {
          callback(new Error('请输入正整数'))
        } else {
          callback()
        }
      }, 100)
    }
    return {
      // 下拉列表
      options: {
        brandOptions: [],
        gTypeOptions: [],
        parentOptions: [],
        attrOptions: [],
        attrTreeOptions: [],
        rowAttrOptions: [],
        attrOptionsMap: {},
      },
      dialogInfo: {
        attrParams: {
          typeId: '',
          attrIds: [],
          assorts: []
        }
      },
      // 折叠页
      activeName: 'main',
      // 表单参数
      form: this.generateForm(),
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: '商品名称不能为空', trigger: 'blur' }
        ],
        brandId: [
          { required: true, message: '商品品牌不能为空', trigger: 'blur' }
        ],
        typeId: [
          { required: true, message: '商品类型不能为空', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '商品价格不能为空', trigger: 'blur' },
          { validator: validatePositiveInteger, trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // 实现行拖拽
    const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
    const sortable = Sortable.create(el, {
      handle: '.allowDrag',
      onEnd: evt => {
        const configList = this.form.config.configList
        const targetRow = configList.splice(evt.oldIndex, 1)[0]
        configList.splice(evt.newIndex, 0, targetRow)
        for (let index in configList) {
          configList[index].sort = parseInt(index) + 1
        }
      }
    })
  },
  created() {
    console.log('dict', this.dict.type.sys_normal_disable)
    this.getBrandTreeSelect()
    this.getGTypeTreeSelect()
    this.getRowAttrTreeselect()
  },
  methods: {
    generateForm() {
      return {
        goodsId: null,
        assNumber: null,
        gNumber: null,
        goodsName: null,
        brandId: null,
        typeId: null,
        typeIdList: [],
        price: 0,
        stockQuantity: 0,
        image: null,
        orderNum: null,
        status: '0',
        delFlag: '0',
        remark: null,
        assort: null,// 分类
        assorts: [],
        attrs: [],
        specList: [
          {
            attrId: '',
            attrName: '',
            values: [
              { valueId: '', valueName: '', },
              { valueId: '', valueName: '', }
            ]
          }
        ],
        goodsInfo: {
          list: [],// 商品列表
          defaultHead: [
            { prop: 'goodsName', label: '商品名称' },
            { prop: 'originPrice', label: '进价/元' },
            { prop: 'price', label: '售价/元' },
            { prop: 'stockQuantity', label: '库存' }
          ],
          tableHeader: [
            { prop: 'goodsName', label: '商品名称' },
            { prop: 'originPrice', label: '进价/元' },
            { prop: 'price', label: '售价/元' },
            { prop: 'stockQuantity', label: '库存' }
          ],
        },
        desc: {
          descImages: [],
          content: null,
          remark: null,
          delFlag: '1'
        },
        config: {
          configList: [],
          selectedList: [],
          indexs: [],
          multiple: true,
          loading: false
        },
        params: {
          lbImages: [],
          xqImages: [],
          descImages: []
        }
      }
    },
    resetForm() {
      this.form = this.generateForm()
    },
    /* ****************** 下拉数据获取 ********************* */
    /** 查询商品品牌下拉树结构 */
    getBrandTreeSelect() {
      optionBrandSelect().then(response => {
        this.options.brandOptions = response.data
      })
    },
    /** 查询商品类型下拉树结构 */
    getGTypeTreeSelect() {
      optionGTypeSelect().then(response => {
        this.options.gTypeOptions = response.data
      })
    },
    /** 查询商品属性下拉树结构 */
    getRowAttrTreeselect() {
      let list = []
      optionAttrSelect().then(response => {
        // this.options.attrOptions = this.handleTree(response.data, "attrId", "parentId");
        list = response.data
        this.generateRowAttrOptions(list)
        this.options.rowAttrOptions = list
      })
    },
    /** 属性下拉列表转换 */
    generateRowAttrOptions(options) {
      if (options) {
        options.forEach(item => {
          if (item.object && item.object.valueUnit) {
            item.label = item.label + '【' + item.object.valueUnit + '】'
          }
          if (item.children && item.children.length > 0) {
            this.generateRowAttrOptions(item.children)
          }
        })
      }
    },
    handleTypeInput(val) {
      if (val) {
        this.form.assorts = []
        const type = this.getLastValueByArray(val)
        this.form.typeId = type
        this.getAttrTreeOptions(type)
      }
    },
    /** 类型属性 */
    getAttrTreeOptions(typeId) {
      if (typeId) {
        optionAttrSelect(typeId).then(res => {
          let list = []
          let attrOptionsMap = {}
          const attrTreeOptions = res.data
          this.options.attrTreeOptions = attrTreeOptions
          attrTreeOptions.filter(o => {
            console.log('attr', o)
            const attrList = this.generateAttrOptions(o)
            list.push(...attrList)
            attrList.filter(o => {
              attrOptionsMap[o.key] = o;
            })
          })
          this.options.attrOptions = list
          this.options.attrOptionsMap = attrOptionsMap
        })
      } else {
        this.options.attrOptions = []
      }
    },
    generateAttrOptions(options) {
      let list = []
      if (options) {
        if (options.children) {
          list.push({ key: options.id + '', label: options.label, code: options.object.attrCode, object: options.object, disabled: true })
          options.children.filter(c => {
            list.push(...this.generateAttrOptions(c))
          })
        } else {
          list.push({ key: options.id + '', label: options.label, code: options.object.attrCode, object: options.object, disabled: options.disabled })
        }
      }
      return list
    },
    /* ****************** 下拉数据获取 end ********************* */
    /* ****************** 图片选择 ********************* */
    /** 打开授权用户表弹窗 */
    openSelectFmImage() {
      this.$refs.selectFm.show()
    },
    openSelectLbImage() {
      this.$refs.selectLb.show()
    },
    openSelectXqImage() {
      this.$refs.selectXq.show()
    },
    handleSelectFmOk(val) {
      if (val && val.length === 1) {
        const image = val[0]
        this.form.imageId = image.imageId
        this.form.image = image.imagePath
      }
    },
    /** 选择图片后 */
    handleSelectLbOk(val) {
      if (val && val.length >= 1) {
        const images = val.map(o => o.imagePath)
        this.form.params.lbImages.push(...images)
      }
    },
    handleSelectXqOk(val) {
      if (val && val.length >= 1) {
        const images = val.map(o => o.imagePath)
        this.form.desc.descImages.push(...images)
      }
    },
    handleDelLbImage(index) {
      let images = this.form.params.lbImages
      if (images && index >= 0 && index <= images.length - 1) {
        images.splice(index, 1)
      }
    },
    handleDelXqImage(index) {
      let images = this.form.desc.descImages
      if (images && index >= 0 && index <= images.length - 1) {
        images.splice(index, 1)
      }
    },
    /* ****************** 图片选择 end ********************* */

    submitMainForm() {
      if (this.form.goodsId == null) {
        addMain(this.form).then(res => {
          this.$modal.msgSuccess('新增成功')
          this.visible = false
          const gNumber = res.data
          // this.$emit('success', gNumber)
        })
      }
    },
    /* ****************** 商品配置 方法 ********************* */
    handleRightCheckChange(targetKeys, direction, moveKeys) {
      console.log('targetKeys:', targetKeys)
      console.log('direction:', direction) // "left" 或 "right"
      console.log('moveKeys:', moveKeys) // 移动的 keys
      // targetKeys = []
    },
    handleTransferChange(targetKeys, direction, moveKeys) {
      console.log('value:', targetKeys)
      console.log('direction:', direction) // "left" 或 "right"
      console.log('movedKeys:', moveKeys) // 移动的 keys

      this.generateTableHeader(targetKeys)
      // targetKeys
      // const goodsInfo = this.form.config.goodsInfo;
      // goodsInfo.tableHeader = [].push(...goodsInfo.defaultHead, ...targetKeys);
    },
    generateTableHeader(keys) {
      const goodsInfo = this.form.goodsInfo;
      console.log('goodsInfo', goodsInfo)
      console.log('options', this.options)
      const tableHeader = []
      tableHeader.push(...goodsInfo.defaultHead)
      if (keys && keys.length > 0) {
        const attrOptionsMap = this.options.attrOptionsMap;
        keys.forEach(item => {
          const attr = attrOptionsMap[item];
          console.log(attr)
          tableHeader.push({ prop: attr.code, label: attr.label, inputType: 'input' })
        })
      }
      goodsInfo.tableHeader = tableHeader
    },
    handleRowInputChange(index, row) {
      console.log('第', index, '行数据变化:', row);
    },
    /** 添加一个商品 */
    handleGoodsAdd() {
      const list = this.form.goodsInfo.list;
      const line = {
        'goodsName': '防盗门1',
        'price': '100',
        'stockQuantity': '99',
      }
      list.push(line);
    },
    /* ******************商品配置  方法end******************** */
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.assort = this.form.assorts ? '' : this.listToString(this.form.assorts)
          if (!this.form.image) {
            this.$modal.msgError('请先选择图片')
          } else {
            this.submitMainForm()
          }
        }
      })
    },
    // 取消按钮
    close() {
      this.$tab.closePage()
    },
    /* *******************属性配置 方法*********************** */
    /** 属性表头自定义 */
    renderHeader(h, { column }) {
      let desc
      if (column.label == '属性名称') {
        desc = '依据属性自动生成，不选择已有属性时，可自定义。'
      } else if (column.label == '属性值') {
        desc = '根据属性获取属性值列表，也可直接输入自定义属性值'
      } else if (column.label == '自定义属性值') {
        desc = '自定义属性，需要附加单位'
      }
      if (desc) {
        return [
          // 自定义图标
          <el-tooltip content={desc} placement="top">
            <i class="el-icon-question"></i>
          </el-tooltip>,
          // 自定义文本
          <span>&nbsp;{column.label}</span>
        ]
      } else {
        return null
      }
    },
    /** 新增配置信息按钮 */
    handleConfigAdd() {
      const typeId = this.form.typeId
      if (!typeId) {
        this.$modal.msgError('请先选择添加商品的类型')
        return
      }
      const attrIds = this.form.config.configList.filter(item => item.attrId != null && item.attrId != undefined).map(item => item.attrId)
      const param = { 'typeId': typeId, 'attrIds': attrIds, assorts: this.form.assorts }
      this.$refs.selectAttr.show(param)
    },
    async handleSelectAttr(val) {
      this.form.config.loading = true
      const selectAttrList = val
      let list = []
      for (let i = 0; i < selectAttrList.length; i++) {
        let attrValOptions = []
        let configName = null
        let multiple = false
        await getAttr(selectAttrList[i].attrId).then(r => {
          attrValOptions = r.data.sprdGoodsAttrValList
          configName = r.data.attrName
          multiple = 'Y' == r.data.valueRadio
        })
        const line = {
          attrId: selectAttrList[i].attrId,
          attr: this.getCascaderVal(this.options.rowAttrOptions, selectAttrList[i].attrId),
          configName: configName,
          valueId: null,
          delFlag: '0',
          attrValOptions: attrValOptions,
          multiple: multiple
        }
        list.push(line)
      }
      this.form.config.configList.push(...list)
      this.form.config.loading = false
    },
    /** 新增一行按钮 */
    handleConfigAddLine() {
      const line = {
        // gNumber: this.gNumber,
        valueId: null,
        delFlag: '0',
        attrValOptions: []
      }
      this.form.config.configList.push(line)
    },
    /** 删除所选行 按钮 */
    handleConfigDel() {
      if (this.form.config.selectedList.length == 0) {
        this.$modal.msgError('请先选择要删除的商品属性配置数据')
      } else {
        const configList = this.form.config.configList
        const indexs = this.form.config.indexs
        this.form.config.configList = configList.filter(item => indexs.indexOf(item.index) == -1)
      }
    },
    /** 商品属性值序号 */
    configRowClassName({ row, rowIndex }) {
      row.index = rowIndex + 1
      let rowClass = ''
      if (row.gConfigId) {
        rowClass += ' info-row'
      }
      if (this.form.assort && this.form.assort.split(',').includes(row.attrId + '')) {
        rowClass += ' required'
      }
      console.log('configRowClassName', rowIndex, 'rowClass:', rowClass, 'assort:', this.form.assorts)
      console.log('form', this.form)
      return rowClass
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.form.config.selectedList = selection
      this.form.config.indexs = selection.map(item => item.index)
      // this.config.single = selection.length != 1;
      this.form.config.multiple = !selection.length
    },
    /** 属性下拉列表修改事件 */
    handleAttrIdChange(row, val) {
      console.log('handleAttrIdChange', row, val)
      row.valueId = null
      row.valueName = null
      row.attrValOptions = []
      let attrId = this.getLastValueByArray(val)
      if (attrId) {
        row.attrId = attrId
        getAttr(attrId).then(res => {
          row.attrValOptions = res.data.sprdGoodsAttrValList
          row.configName = res.data.attrName
          row.multiple = 'Y' === res.data.valueRadio
        })
      }
    },
    /** 属性下拉列表修改事件 */
    handleAttrValChange(row, val) {
      if (row.multiple) {
        let values = val
        let valueId = ''
        let valueName = ''
        if (values && values.length > 0) {
          values.filter(v => {
            valueId += v + ','
            let attrValOption = row.attrValOptions.find(o => o.valueId == v)
            if (attrValOption) {
              valueName += attrValOption.valueLabel + ', '
            } else {
              valueName += v + ', '
            }
          })
        }
        row.valueName = valueName.substring(0, valueName.length - 2)
        row.valueId = valueId.substring(0, valueId.length - 1)
      } else {
        let attrValOption = row.attrValOptions.find(o => o.valueId == val)
        if (attrValOption) {
          row.valueName = attrValOption.valueLabel
        } else {
          row.valueName = val
        }
      }
    },
    /* *******************属性配置 方法 end*********************** */
    withoutAssorts() {
      if (this.form.assorts) {
        return this.form.assorts.length === 0
      } else {
        return true
      }
    },
    /** 获取 cascader 值的末位 id */
    getLastValueByArray(arr) {
      if (arr && arr.length > 0) {
        return arr[arr.length - 1]
      }
      return null
    },
    /** 通过id 转换为 cascader 值 */
    getCascaderVal(options, value) {
      let result = []
      if (options && value) {
        options.some(o => {
          if (o.id == value) {
            result = [o.value]
            return true
          }
          if (o.children) {
            let bo = false
            o.children.some(c => {
              if (c.id == value) {
                result = [o.value, c.value]
                bo = true
                return true
              }
            })
            if (bo) {
              return bo
            }
          }
        })
      }
      return result
    }
  }
}
</script>

<style scoped>
/*.goods-info-container {
  position: relative;
}

.flex-buttons {
  position: absolute;
  top: 21px;
  right: 20px;
}*/

.goods-info-header {
  display: flex;
  justify-content: space-between;
  padding: 10px 5px;

  .goods-info-header-title {
    font-size: 18px;
    font-weight: 500;
  }
}

.image-list {
  display: inline-block;
  width: calc(100% - 180px);
  margin-left: 170px;
}

.image-item {
  width: 80px;
  display: inline-grid;
  margin-left: 10px;
}
</style>
